package com.atguigu.java.ai.langchain4j.store;

import com.atguigu.java.ai.langchain4j.bean.ChatForm;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * @Author: Mikey
 * @Date: 2025/9/4 14:41
 * @Description:
 **/
@Component
public class MongoChatMemoryStore implements ChatMemoryStore {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        //查询该条文档是否存在
        Query query = new Query(Criteria.where("memoryId").is(memoryId));
        ChatForm chatForm = mongoTemplate.findOne(query, ChatForm.class);
        //判断是否为空 若为空返回空集合 不为空序列化返回数据
        if(chatForm==null){
            return Collections.emptyList();
        }

        //序列化数据返回
        return ChatMessageDeserializer.messagesFromJson(chatForm.getMessage());
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        //查询该条数据进行修改   若不存在就新增
        Query query = new Query(Criteria.where("memoryId").is(memoryId));
//        ChatForm chatForm = mongoTemplate.findOne(query, ChatForm.class);
        Update update = new Update();
        //反序列化集合进行修改或新增
        update.set("message", ChatMessageSerializer.messagesToJson(messages));

        //进行处理
        mongoTemplate.upsert(query,update,ChatForm.class);

    }

    @Override
    public void deleteMessages(Object memoryId) {
        //进行删除
        Query query = new Query(Criteria.where("memoryId").is(memoryId));

        mongoTemplate.remove(query,ChatForm.class);

    }
}
